<?php

namespace App\Http\Controllers\Admin;

use App\Model\SaAdmin;
use App\Rules\AdminRule;
use App\Service\AdminService;

class AdminController extends BaseController
{
    /**
     * 获取管理员列表.
     */
    public function getAdminList()
    {
        return successJson(AdminService::getAdminList($this->requestArr));
    }

    /**
     * 获取管理员详情.
     */
    public function getAdminInfo()
    {
        $id = $this->requestArr['id'];

        $info = [];
        $data = AdminService::getInfoById($id);
        if ($data) {
            $info['id']       = $data['id'];
            $info['status']   = $data['status'];
            $info['role_id']  = $data['role_id'];
            $info['username'] = $data['username'];
        }

        return successJson($info);
    }

    /**
     * 添加管理员.
     */
    public function addAdmin()
    {
        $username        = $this->requestArr['username'];
        $password        = $this->requestArr['password'];
        $roleId          = $this->requestArr['role_id'];
        $status          = 1 == $this->requestArr['status'] ? 1 : 0;
        $confirmPassword = $this->requestArr['confirm_password'];

        // 验证参数
        $adminRule                = new AdminRule();
        $post                     = compact('username', 'password');
        $post['role_id']          = $roleId;
        $post['confirm_password'] = $confirmPassword;
        if (!$adminRule->scene('add')->check($post)) {
            return failJson($adminRule->getError());
        }

        $result = AdminService::addAdmin($username, $password, $roleId, $status);

        return successJson($result);
    }

    /**
     * 编辑管理员.
     */
    public function editAdmin()
    {
        $id       = $this->requestArr['id'];
        $password = $this->requestArr['password'];
        $roleId   = $this->requestArr['role_id'];
        $status   = 1 == $this->requestArr['status'] ? 1 : 0;

        $result = AdminService::editAdmin($id, $roleId, $status, $password);

        return successJson($result);
    }

    /**
     * 快捷修改管理员.
     */
    public function quickEditAdmin()
    {
        $id             = $this->requestArr['id'];
        $data['status'] = 1 == $this->requestArr['status'] ? 1 : 0;

        $result = SaAdmin::editAdmin($id, $data);

        return successJson($result);
    }

    /**
     * 删除管理员.
     *
     * @throws \Exception
     */
    public function deleteAdmin()
    {
        $id = $this->requestArr['id'];

        if ($id == $this->userId) {
            return failJson('无法自我删除');
        }

        $result = AdminService::delAdminById($id);

        return successJson($result);
    }
}
